<!DOCTYPE html>
<html>

<head>
    <title> How to bind function in React? </title>
    <script src="https://unpkg.com/react@17/umd/react.production.min.js" crossorigin></script>
    <script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js" crossorigin></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js" crossorigin></script>
</head>

<body>
    <div id="root"></div>
</body>

</html>
<script type="text/babel">
    class Toggle extends React.Component {
        constructor(props) {
            super(props);
            this.state = {
                isToogle: true,
            }
        }

        // TODO: 不能打断点
        // Way 4 Depressed. Use arrow function in the callback
        handClick() {
            console.log('handClick this:' + this);
            this.setState(function (prevState) {
                return {
                    isToogle: !prevState.isToogle,
                }
            });
        }

        render() {
            // Problem: 
            // With this syntax that a different callback is created each time when Component renders. In most cases,this is fine. 
            // But If the callback is passed as prop to lower components, those components may do an extra rendering.

            // Q : 为什么每次render会重新create handClick callback？
            // 因为 () => this.handClick()是一个匿名函数，每次render 都要重新创建一个新的handClick callback实例。
            return (<button onClick={() => this.handClick()}>
                {this.state.isToogle ? "ON" : "OFF"}
            </button>);
        }
    }

    ReactDOM.render(<Toggle />, document.getElementById('root'));
</script>